package com.cw.lang.common.framework.feign;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import com.cw.base.common.model.constants.RestConstant;
import com.cw.base.common.model.dto.base.BaseReqDto;
import com.cw.base.common.model.dto.base.BaseUserReqDto;
import com.cw.lang.common.framework.converter.BaseRequestConverter;
import com.cw.lang.common.framework.converter.BaseUserRequestConverter;
import com.cw.lang.common.utils.context.ThreadContextStoreUtil;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * @author chenw
 * @version $$Id: BaseRequestHeaderInterceptor.java, v 0.1 2018/10/21 9:58 PM chenw Exp $$
 */
@Order(Ordered.HIGHEST_PRECEDENCE + 10000)
public class RequestHeaderInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        template.header(RestConstant.RPC_BASE_REQUEST, getBaseRequest());
        template.header(RestConstant.RPC_BASE_USER_REQUEST, getBaseUserRequest());
    }

    /**
     * 从线程上下文上获取{@link BaseReqDto}
     *
     * @return {@link BaseReqDto}
     */
    private String getBaseRequest() {
        return BaseRequestConverter.encode((BaseReqDto) ThreadContextStoreUtil.getInstance()
            .get(RestConstant.RPC_BASE_REQUEST));
    }

    /**
     * 从线程上下文上获取{@link BaseUserReqDto}
     *
     * @return {@link BaseUserReqDto}
     */
    private String getBaseUserRequest() {
        return BaseUserRequestConverter.encode((BaseUserReqDto) ThreadContextStoreUtil.getInstance()
            .get(RestConstant.RPC_BASE_USER_REQUEST));
    }

}
